<template>
  <div class="admin-delivery-management">
    <div class="page-header">
      <h2 class="page-title">配送管理</h2>
      <div class="header-divider"></div>
      <div class="search-row">
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="配送编号">
            <el-input v-model="searchForm.delivery_number" placeholder="请输入配送编号" clearable @input="handleDeliveryNumberInput" />
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 120px;">
              <el-option label="全部" value="" />
              <el-option label="待处理" value="pending" />
              <el-option label="已分配" value="assigned" />
              <el-option label="配送中" value="delivering" />
              <el-option label="已完成" value="completed" />
              <el-option label="已取消" value="cancelled" />
            </el-select>
          </el-form-item>
          <el-form-item label="配送员">
            <el-select
              v-model="searchForm.deliveryman_id"
              placeholder="请选择配送员"
              clearable
              filterable
              @change="handleDeliverymanChange"
              style="width: 180px;"
            >
              <el-option
                v-for="staff in deliveryStaff"
                :key="staff.user ? staff.user.id : staff.id"
                :label="staff.user ? staff.user.username : '未知'"
                :value="staff.user ? staff.user.id : staff.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">筛选</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
        <el-button type="success" size="default" @click="refreshDeliveries" class="refresh-btn">刷新数据</el-button>
      </div>
      <div class="divider"></div>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="6" animated />
    </div>

    <!-- 配送任务列表 -->
    <div class="table-wrapper" v-if="!loading">
      <el-table :data="deliveries" style="width: 100%">
        <el-table-column prop="delivery_number" label="配送编号" width="180" />
        <el-table-column prop="order_number" label="关联订单" width="180" />
        <el-table-column prop="deliveryman_name" label="配送员" width="120">
          <template #default="scope">
            <el-tag v-if="scope.row.deliveryman_name" type="info">{{ scope.row.deliveryman_name }}</el-tag>
            <el-tag v-else type="danger">未分配</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="sales_order_detail.payment_time" label="下单时间" width="180">
          <template #default="{ row }">
            <span v-if="row.sales_order_detail && row.sales_order_detail.payment_time && !isNaN(new Date(row.sales_order_detail.payment_time).getTime())">
              {{ new Date(row.sales_order_detail.payment_time).toLocaleString() }}
            </span>
            <span v-else style="color: #ccc;">--</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <el-button type="success" link @click="handleViewDetails(row)">查看详情</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新建/编辑配送任务对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑配送任务' : '新建配送任务'"
      width="50%"
    >
      <el-form :model="deliveryForm" label-width="100px">
        <el-form-item label="关联订单">
          <el-select v-model="deliveryForm.sales_order" placeholder="请选择订单" filterable>
            <el-option
              v-for="order in availableOrders"
              :key="order.id"
              :label="`${order.order_number} - ${order.customer_name}`"
              :value="order.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="优先级">
          <el-select v-model="deliveryForm.priority" placeholder="请选择优先级">
            <el-option label="高" value="high" />
            <el-option label="中" value="medium" />
            <el-option label="低" value="low" />
          </el-select>
        </el-form-item>
        <el-form-item label="预计配送时间">
          <el-date-picker
            v-model="deliveryForm.estimated_delivery_time"
            type="datetime"
            placeholder="选择日期时间"
          />
        </el-form-item>
        <el-form-item label="备注">
          <el-input type="textarea" v-model="deliveryForm.note" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmitDelivery">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 分配配送员对话框 -->
    <el-dialog
      v-model="assignDialogVisible"
      title="分配配送员"
      width="50%"
    >
      <el-form :model="assignForm" label-width="100px">
        <el-form-item label="配送任务">
          <span>{{ assignForm.delivery_number }}</span>
        </el-form-item>
        <el-form-item label="配送员">
          <el-select v-model="assignForm.deliveryman_id" placeholder="请选择配送员" filterable>
            <el-option
              v-for="staff in deliveryStaff"
              :key="staff.id"
              :label="`${staff.user ? staff.user.username : '未知'} (ID: ${staff.id})`"
              :value="staff.user ? staff.user.id : staff.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="优先级">
          <el-select v-model="assignForm.priority" placeholder="请选择优先级">
            <el-option label="高" value="high" />
            <el-option label="中" value="medium" />
            <el-option label="低" value="low" />
          </el-select>
        </el-form-item>
        <el-form-item label="预计配送时间">
          <el-date-picker
            v-model="assignForm.estimated_delivery_time"
            type="datetime"
            placeholder="选择日期时间"
          />
        </el-form-item>
        <el-form-item label="备注">
          <el-input type="textarea" v-model="assignForm.note" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="assignDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmitAssign">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'
import { getToken } from '@/utils/auth'

// 配送任务列表数据
const deliveries = ref([])
const loading = ref(false)

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const deliveriesAll = ref([]) // 存储所有配送任务数据

// 搜索表单
const searchForm = ref({
  delivery_number: '',
  status: '',
  deliveryman_id: ''
})

// 可用订单列表
const availableOrders = ref([])

// 配送员列表
const deliveryStaff = ref([])

// 对话框相关
const dialogVisible = ref(false)
const isEdit = ref(false)
const deliveryForm = ref({
  sales_order: '',
  priority: 'medium',
  estimated_delivery_time: '',
  note: ''
})

// 分配对话框相关
const assignDialogVisible = ref(false)
const assignForm = ref({
  id: '',
  delivery_number: '',
  deliveryman_id: '',
  priority: '',
  estimated_delivery_time: '',
  note: ''
})

// 获取状态样式
const getStatusType = (status) => {
  const statusMap = {
    'pending': 'warning',
    'assigned': 'info',
    'delivering': 'primary',
    'completed': 'success',
    'cancelled': 'danger'
  }
  return statusMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    'pending': '待处理',
    'assigned': '已分配',
    'delivering': '配送中',
    'completed': '已完成',
    'cancelled': '已取消'
  }
  return statusMap[status] || status
}

// 获取配送任务列表
const fetchDeliveries = async () => {
  try {
    const token = getToken()
    if (!token) {
      ElMessage.warning('请先登录')
      return
    }

    const response = await axios.get('/api/delivery-tasks/', {
      params: {
        page: 1,
        page_size: 1000 // 获取所有数据用于本地分页
      },
      headers: {
        'Authorization': `Bearer ${token}`
      }
    })
    const data = response.data.data
    deliveriesAll.value = data.items || []
    filterDeliveries() // 初始渲染
  } catch (error) {
    console.error('获取配送任务列表失败:', error)
    ElMessage.error('获取配送任务列表失败: ' + (error.response?.data?.detail || error.message))
  }
}

// 本地过滤和分页
const filterDeliveries = () => {
  let filtered = deliveriesAll.value

  // 配送编号模糊匹配
  if (searchForm.value.delivery_number) {
    const q = searchForm.value.delivery_number.trim()
    filtered = filtered.filter(delivery => (delivery.delivery_number || '').includes(q))
  }
  // 状态等值匹配
  if (searchForm.value.status) {
    filtered = filtered.filter(delivery => delivery.status === searchForm.value.status)
  }
  // 配送员ID筛选
  if (searchForm.value.deliveryman_id) {
    filtered = filtered.filter(delivery => {
      // 支持deliveryman、deliveryman_id、deliveryman_name等多种结构
      return (
        String(delivery.deliveryman) === String(searchForm.value.deliveryman_id) ||
        String(delivery.deliveryman_id) === String(searchForm.value.deliveryman_id) ||
        (delivery.deliveryman && delivery.deliveryman.user && String(delivery.deliveryman.user.id) === String(searchForm.value.deliveryman_id))
      )
    })
  }

  // 调整顺序：将已取消的放最后
  filtered = [
    ...filtered.filter(d => d.status !== 'cancelled'),
    ...filtered.filter(d => d.status === 'cancelled')
  ]

  // 更新总数
  total.value = filtered.length

  // 分页处理
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  deliveries.value = filtered.slice(start, end)
}

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1
  filterDeliveries()
}

// 处理重置
const handleReset = () => {
  searchForm.value = {
    delivery_number: '',
    status: '',
    deliveryman_id: ''
  }
  currentPage.value = 1
  filterDeliveries()
}

// 处理分页大小变化
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  filterDeliveries()
}

// 处理页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val
  filterDeliveries()
}

// 获取可用订单列表
const fetchAvailableOrders = async () => {
  try {
    const token = getToken()
    if (!token) {
      ElMessage.warning('请先登录')
      return
    }
    
    const response = await axios.get('/api/orders/', {
      params: {
        status: 'paid',  // 只获取已支付的订单
        has_delivery: false  // 没有配送任务的订单
      },
      headers: {
        'Authorization': `Bearer ${token}`
      }
    })
    
    if (response.data.code === 200) {
      // 修改这里，使用items而不是results
      availableOrders.value = response.data.data.items
    } else {
      ElMessage.error(response.data.message || '获取可用订单列表失败')
    }
  } catch (error) {
    console.error('获取可用订单列表出错:', error)
    ElMessage.error('获取可用订单列表失败: ' + error.message)
  }
}

// 获取配送员列表
const fetchDeliveryStaff = async () => {
  try {
    const token = getToken()
    if (!token) {
      ElMessage.warning('请先登录')
      return
    }
    
    const response = await axios.get('/api/delivery-staff', {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    })
    
    // 修改开始：直接使用 response.data 作为配送员列表
    // 并检查返回的是否为数组
    if (Array.isArray(response.data)) {
      deliveryStaff.value = response.data
      console.log('配送员列表:', deliveryStaff.value)
    } else {
      // 如果不是预期的数组格式，记录错误，并尝试从常见的错误结构中获取消息
      console.error('获取配送员列表失败，响应数据格式不正确:', response.data)
      ElMessage.error(response.data.message || response.data.detail || '获取配送员列表失败，响应格式错误')
    }
    // 修改结束
  } catch (error) {
    console.error('获取配送员列表出错:', error)
    ElMessage.error('获取配送员列表失败: ' + error.message)
  }
}

// 刷新配送任务列表
const refreshDeliveries = () => {
  fetchDeliveries()
}

// 处理编辑配送任务
const handleEditDelivery = (row) => {
  isEdit.value = true
  dialogVisible.value = true
  deliveryForm.value = {
    id: row.id,
    sales_order: row.sales_order,
    priority: row.priority,
    estimated_delivery_time: row.estimated_delivery_time,
    note: row.note
  }
}

// 处理查看详情
const handleViewDetails = (row) => {
  ElMessageBox.alert(
    `配送编号: ${row.delivery_number}<br/>
     关联订单: ${row.order_number}<br/>
     客户名称: ${row.customer_name}<br/>
     配送地址: ${row.address}<br/>
     配送员: ${row.deliveryman_name || '未分配'}<br/>
     状态: ${getStatusText(row.status)}<br/>
     优先级: ${row.priority}<br/>
     预计配送时间: ${row.estimated_delivery_time || '未设置'}<br/>
     实际配送时间: ${row.actual_delivery_time || '未完成'}<br/>
     备注: ${row.note || '无'}<br/>
     创建时间: ${row.created_at}<br/>
     更新时间: ${row.updated_at}`,
    '配送任务详情',
    {
      dangerouslyUseHTMLString: true,
      confirmButtonText: '确定'
    }
  )
}

// 处理分配配送员
const handleAssignDelivery = (row) => {
  assignDialogVisible.value = true
  assignForm.value = {
    id: row.id,
    delivery_number: row.delivery_number,
    deliveryman_id: row.deliveryman?.id || '',
    priority: row.priority,
    estimated_delivery_time: row.estimated_delivery_time,
    note: row.note
  }
  fetchDeliveryStaff()
}

// 提交配送任务
const isSuccess = (response) => {
  return (response.data && response.data.code === 200) || response.status === 200
}

const handleSubmitDelivery = async () => {
  try {
    const token = getToken()
    if (!token) {
      ElMessage.warning('请先登录')
      return
    }
    if (!deliveryForm.value.sales_order) {
      ElMessage.warning('请选择关联订单')
      return
    }
    // 前端校验：防止重复提交同一订单
    if (!isEdit.value) {
      const exists = deliveries.value.some(d => d.sales_order === deliveryForm.value.sales_order)
      if (exists) {
        ElMessage.error('该订单已存在配送任务，请勿重复分配！')
        return
      }
    }
    const url = isEdit.value 
      ? `/api/delivery-tasks/${deliveryForm.value.id}/` 
      : '/api/delivery-tasks/'
    const method = isEdit.value ? 'put' : 'post'
    const response = await axios({
      url,
      method,
      data: deliveryForm.value,
      headers: {
        'Authorization': `Bearer ${token}`
      }
    })
    if (isSuccess(response)) {
      ElMessage.success(isEdit.value ? '更新成功' : '创建成功')
      dialogVisible.value = false
      fetchDeliveries()
      if (!isEdit.value) fetchAvailableOrders() // 新建后刷新可用订单
    } else {
      ElMessage.error((response.data && response.data.message) || (isEdit.value ? '更新失败' : '创建失败'))
    }
  } catch (error) {
    if (error.response && error.response.status === 400 && error.response.data) {
      // 展示后端详细错误
      const msg = Object.values(error.response.data).flat().join('; ')
      ElMessage.error((isEdit.value ? '更新失败: ' : '创建失败: ') + msg)
    } else if (error.response && error.response.status === 500) {
      ElMessage.error('后端服务异常，请联系管理员修复接口权限配置')
    } else {
      ElMessage.error((isEdit.value ? '更新失败: ' : '创建失败: ') + error.message)
    }
  }
}

// 提交分配配送员
const handleSubmitAssign = async () => {
  try {
    const token = getToken()
    if (!token) {
      ElMessage.warning('请先登录')
      return
    }
    
    if (!assignForm.value.deliveryman_id) {
      ElMessage.warning('请选择配送员')
      return
    }
    
    const response = await axios.post(
      `/api/delivery-tasks/${assignForm.value.id}/assign/`,
      {
        deliveryman_id: assignForm.value.deliveryman_id,
        priority: assignForm.value.priority,
        estimated_delivery_time: assignForm.value.estimated_delivery_time,
        note: assignForm.value.note
      },
      {
        headers: {
          'Authorization': `Bearer ${token}`
        }
      }
    )
    
    if (response.data.code === 200) {
      ElMessage.success('分配成功')
      assignDialogVisible.value = false
      fetchDeliveries()
    } else {
      ElMessage.error(response.data.message || '分配失败')
    }
  } catch (error) {
    console.error('分配配送员出错:', error)
    ElMessage.error('分配失败: ' + error.message)
  }
}

// 处理配送员变化
const handleDeliverymanChange = () => {
  currentPage.value = 1
  filterDeliveries()
}

// 实时筛选配送编号
const handleDeliveryNumberInput = () => {
  currentPage.value = 1
  filterDeliveries()
}

// 页面加载时获取数据
onMounted(() => {
  fetchDeliveryStaff()
  fetchDeliveries()
})
</script>

<style scoped>
.admin-delivery-management {
  padding: 0;
  background: #fff;
}

.page-header {
  background: #fff;
  padding: 24px 24px 0 24px;
  border-radius: 0;
}

.table-wrapper {
  padding-left: 24px;
  padding-right: 24px;
  background: #fff;
  overflow-x: auto;
}

.table-wrapper .el-table {
  min-width: 900px;
}

.page-title {
  font-size: 28px;
  font-weight: bold;
  margin: 0 0 8px 0;
  color: #222;
}

.header-divider {
  border-bottom: 1px solid #f0f0f0;
  margin-bottom: 18px;
}

.search-row {
  display: flex;
  align-items: flex-end;
  background: #fff;
  padding-bottom: 12px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  margin-bottom: 0;
}

.refresh-btn {
  margin-left: 16px;
  align-self: flex-start;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.loading-container {
  padding: 20px;
}

.divider {
  border-bottom: 1px solid #f0f0f0;
  margin: 0 24px 18px 24px;
}
</style>